package com.jiangyg.mall.core.support.validation.constraints;

import com.jiangyg.mall.core.support.validation.AbstractConstraintValidator;
import org.hibernate.validator.internal.engine.constraintvalidation.ConstraintValidatorContextImpl;

import javax.validation.Constraint;
import javax.validation.Payload;
import java.lang.annotation.Documented;
import java.lang.annotation.Retention;
import java.lang.annotation.Target;

import static java.lang.annotation.ElementType.*;
import static java.lang.annotation.RetentionPolicy.RUNTIME;

/**
 * 类描述：验证int数值，满足指定任意值即可
 *
 * @author jiangyg
 * @date 2021-09-30
 */
@Documented
@Retention(RUNTIME)
@Constraint(validatedBy = {IntAnyValue.IntAnyValueConstraintValidator.class})
@Target({METHOD, FIELD, ANNOTATION_TYPE, CONSTRUCTOR, PARAMETER, TYPE_USE})
public @interface IntAnyValue {

    int[] value() default {};

    String message() default "{custom.validation.constraints.IntAnyValue.message}";

    /**
     * 分组，用于判断在那种情况下执行校验
     */
    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    /**
     * 类描述：验证int数值执行器
     *
     * @author jiangyg
     * @version 2.0
     * @date 2021-09-30
     */
    class IntAnyValueConstraintValidator extends AbstractConstraintValidator<IntAnyValue, Integer> {

        @Override
        public boolean execute(IntAnyValue a, Integer value, ConstraintValidatorContextImpl contextImpl) {
            final int[] vals = a.value();
            if (value == null) {
                return false;
            }
            for (int val : vals) {
                if (val == value) {
                    return true;
                }
            }
            return false;
        }

    }

}
